package com.xr.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtil {

    /**
     * 通过url读取文件
     *
     * @param url 路径
     */
    public static byte[] getFileStream(String url) {
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            // 通过输入流获取文件数据
            InputStream inputStream = conn.getInputStream();
            return readInputStream(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     *
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 下载文件到本地
     *
     * @param url      文件全路径 + 文件名
     * @param localUrl 下载到本地的路径，例：windows:C:/images/、linux:/usr/local/images/
     */
    public static String downloadFileToLocal(String url, String localUrl) {
        // 将网络文件下载本地
        try {
            byte[] data = FileUtil.getFileStream(url);
            String substring = url.substring(url.lastIndexOf("/") + 1);
            String name = localUrl + substring;
            // 创建一个文件对象
            File file = new File(name);
            // 创建输出流
            FileOutputStream outStream = new FileOutputStream(file);
            // 写入数据
            assert data != null;
            outStream.write(data);
            // 关闭输出流，释放资源
            outStream.close();
            return name;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
